package com.heng.locks;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class InterruptDemo7 {
    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);


    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true，程序停止");
                    break;
                }
                System.out.println("t1---hello interrupt api");
            }
        }, "t1");

        t1.start();

        new Thread(()-> {
            t1.interrupt();
        },"t2").start();
    }

//线程与线程之间的协作
    @Test
    public void m2() {
        new Thread(() -> {
            while (true){
                if(atomicBoolean.get()){
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true，程序停止");
                    break;
                }
                System.out.println("t1---hello volatile");
            }
        },"t1").start();
        try {TimeUnit.MILLISECONDS.sleep(20);}catch (InterruptedException e) {e.printStackTrace();}

        new Thread(()-> {
            atomicBoolean.set(true);
        },"t2").start();
    }


    @Test
    public void m1() {
        new Thread(() -> {
            while (true){
                if(isStop){
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true，程序停止");
                    break;
                }
                System.out.println("t1---hello volatile");
            }
        },"t1").start();

        try {TimeUnit.MILLISECONDS.sleep(20);}catch (InterruptedException e) {e.printStackTrace();}

        new Thread(()-> {
            isStop = true;
        },"t2").start();
    }
}
